package com.longteng.diamond.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by Administrator
 * DATE : 2018/8/15
 * TIME : 22:58
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Configuration
public class ThreadPoolConfig {
    /**
    * 核心线程数
    * */
    @Value("${core.pool.size}")
    private int corePoolSize;
    /**
     * 最大线程数
     * **/
    @Value("${max.pool.size}")
    private int maxPoolSize;

    /**
     * 队列容量
     * **/
    @Value("${queue.capacity}")
    private int queueCapacity;

    @Bean
    public Executor taskPool(){
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("MyExecutor-");
        /**
         * rejected-policy:当pool已经达到max size的时候,如何处理新任务
         * caller-runs:不在新现成中执行任务,而是由调用者所在的线程来执行
         * **/
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
